<template>
  <div class="email-card" :class=" tabType === 'email_todo' ? 'email_todo' : 'email_all'">
    <el-menu
        :default-active = "defaultActive"
        @select="handleSelect"
        :router="active"
        class="el-menu-vertical-demo">
      <el-menu-item style="padding: 0" v-for="(item, index) in cardListRender" :index="handleSplit(item._id)" :class="{'custom-is-active': $route.path.split('/')[4] === item._id}" :key="item._id">
        <div class="card email_card_li" :class="{'all': tabType === 'email_all'}">
          <!-- 批量选择按钮 -->
          <label v-show="tabType === 'email_todo' || (tabType === 'email_all' && shouFinshUndeal && searchStatus === 'undeal')" class="fake-checkbox" :class="{'visible': batch[tabType].isBatchShow}" v-on:click.stop="">
            <input type="checkbox" class="fbox" :value="item._id" v-model.trim="item.checked" @change="checkThis(item.checked)">
            <span></span>
            <i class="fake-label"></i>
          </label>
          <!-- 用于撑开的标签 -->
          <span class="ct">
          </span>
          <!-- 待处理邮件 -->
          <template v-if="tabType === 'email_todo'">
            <ul class="info">
              <!-- 客户名称（第一行） -->
              <li class="email_info_subject font12 clearfix">
                <div class="email_card_flex">
                  <h4 class="ellipsis card_left" :title="item.custName ? item.custName : item.from.name + '<' + item.from.addr + '>'">{{item.custName ? item.custName : item.from.name + "<" + item.from.addr + ">" }} </h4>
                  <!-- 邮件时间 -->
                  <span class="ellipsis card_right email_chat_time">{{ item.chatTime }}</span>
                </div>
              </li>
              <!-- 邮件标题（第二行） -->
              <li class="email_info_from clearfix">
                <div class="email_card_flex">
                  <!-- 星标 -->
                  <i class="el-icon-star-on" v-if="item.mailMarks && item.mailMarks.starMark ==='mark'"></i>
                  <!-- 邮件标题 -->
                  <span class="ellipsis card_left" :class="item.leakNum ? '' : 'leak_no'" :title="item.subject">{{item.subject}}</span>
                  <dd class="card_right">
                    <span v-if="item.leakNum" class="leak_num">{{item.leakNum}}</span>
                    <!-- 客户状态 -->
                    <span class="cust_status" :style="{color: currentColor(item.cust_status)}">{{statusName(item.cust_status)}}</span>
                  </dd>
                </div>
              </li>
            </ul>
          </template>

          <!-- 全部邮件 -->
          <template v-else>
            <ul class="info">
              <!-- 客户名称（第一行） -->
              <li class="email_info_subject font12 clearfix">
                <div class="email_card_flex">
                  <h4 class="ellipsis card_left" :title="item.custName ? item.custName : item.from.name + '<' + item.from.addr + '>'">{{item.custName ? item.custName : item.from.name + "<" + item.from.addr + ">" }} </h4>
                  <span class="ellipsis card_right email_chat_time">{{ item.chatTime }}</span>
                </div>
              </li>
              <!-- 邮件标题&&邮件处理状态（第二行） -->
              <li class="email_info_from clearfix">
                <div class="email_card_flex">
                  <!-- 邮件星标 -->
                  <i class="el-icon-star-on" v-if="item.mailMarks && item.mailMarks.starMark ==='mark'"></i>
                  <span class="ellipsis card_left" :class="item.leakNum ? '' : 'leak_no'" :title="item.subject">{{item.subject}}</span>
                  <!-- 邮件处理状态 -->
                  <dd class="card_right">
                    <span v-if="item.leakNum" class="leak_num">{{item.leakNum}}</span>
                    <span v-if="item.status === 'undeal' && !item.processTimeout" class="status_undeal card_statu_li clearfix">{{$t('email.Pending')}}</span>
                    <span v-if="item.status === 'deal' && !item.processTimeout" class="status_deal card_statu_li clearfix">{{$t('email.Processing')}}</span>
                    <span v-if="item.status === 'finish'" class="status_finish card_statu_li clearfix">{{$t('email.Solved')}}</span>
                    <span v-if="item.processTimeout && item.status !== 'finish'" class="status_deal card_statu_li clearfix">{{$t('email.timeOut')}}</span>
                  </dd>
                </div>
              </li>
              <!-- 处理坐席&&客户状态 -->
              <li class="email_info_other clearfix">
                <div class="email_card_flex">
                  <!-- 处理坐席和技能组 -->
                  <span class="ellipsis card_left topeer_box"
                        :title="item.agentName ? item.toPeerName ? item.agentName + '(' + item.toPeerName + ')' : item.agentName : ''"
                        v-text="item.agentName ? item.toPeerName ? item.agentName + '(' + item.toPeerName + ')' : item.agentName : ''">
                  </span>
                  <!-- 客户状态 -->
                  <i class="card_right">
                    <span class="cust_status" :style="{color: currentColor(item.cust_status)}">{{statusName(item.cust_status)}}</span>
                  </i>
                </div>
              </li>
            </ul>
          </template>
        </div>
      </el-menu-item>
    </el-menu>
    <no-record v-if="cardList && cardList.length<=0"></no-record>
    <!-- 批处理-->
    <div class="batch_cover" :class="{'navMenuState': navMenuState}" v-show="batch[tabType].isBatchShow"></div>
    <div class="batch_btm" v-show="batch[tabType].isBatchShow"></div>
    <div class="batch" :class="{'show': batch[tabType].isBatchShow, 'navMenuState': navMenuState}">
      <!--结束对话框-->
      <el-checkbox v-model.trim="batch[tabType].allChecked" @change="checkAll()">{{$t('public.checkAll')}}</el-checkbox>
      <card-batch v-if="batch[tabType].operator"
                  :tabType="tabType"
                  :batchOperator="batch[tabType]"
                  @checkNone="checkNone"
                  @showFinishPopup="showFinishPopup"
      ></card-batch>
    </div>
    <!-- 结束会话框 -->
    <end-session-box v-if="batchFinish.dialogTableVisible" :info="batchFinish" @endSession="endSessionFun" @changeEndSiFlag="changeEndSessionFlag"></end-session-box>
  </div>
</template>
<script type="text/javascript">
  import CustomerAvatar from '@/components/ui-modules/customer-avatar/CustomerAvatar'
  import CardBatch from '@/components/public-modules/card/CardBatch'
  import { statusCustColorArr } from '@/utils/reportUtils'
  import { timeFormat, deepClone, getEmailQueueCacheByKey, contains } from '@/utils/m7Utils.js'
  import EndSessionBox from '@/components/public-modules/ImEndSessionBox/EndSessionBox'
  import NoRecord from '@/components/public-modules/card/NoRecord'
  import * as uuid from 'uuid'
  import * as gtypes from '@/store/mutation-types'
  export default {
    name: 'EmailCard',
    props: {
      allCount: Number,
      cardList: Array,
      qu: Object,
      type: String,
      tabType: String,
      searchStatus: String,
      currentAdvSesrch: Object,
      clearChecked: String
    },
    watch: {
      // clearChecked 变化 再次执行
      clearChecked: 'checkNone',
      // cardList 变化 再次执行
      cardList () {
        this.defaultActive = this.$route.path
        this.checkNone()
      },
      $route (to, form) {
        if (to.path.split('/')[2] === 'email') {
          this.defaultActive = to.path
        }
      },
      searchStatus: 'changeSearchStatus'
    },
    components: {
      CustomerAvatar,
      CardBatch,
      EndSessionBox,
      NoRecord
    },
    data () {
      return {
        loading: true,
        checked: false,     // 是否选中
        defaultActive: '',
        active: true, // 是否使用路由
        shouFinshUndeal: false,     // 全部中是否可以展示批量结束的权限
        colors: statusCustColorArr, // 匹配客户的颜色值
        batch: {
          email_todo: {
            batchItem: [],
            allChecked: false,    //  是否全选
            isBatchShow: false,   //  是否批处理
            checkedCount: 0,      //  选中条数
            operator: [           //  批量菜单展示按钮
              {name: 'public.finish', class: 'icon-wancheng1', action: 'showFinishPopup'}
            ]
          },
          email_all: {
            batchItem: [],
            allChecked: false,    //  是否全选
            isBatchShow: false,   //  是否批处理
            checkedCount: 0,      //  选中条数
            operator: [           //  批量菜单展示按钮
//              {name: 'public.export', class: 'icon-daochu1', action: 'exportExcel'},
              {name: 'public.finish', class: 'icon-wancheng1', action: 'showFinishPopup'}
            ]
          }
        },
//        结束会话框参数
        batchFinish: {
          isActiveOne: '999',
          isActiveTwo: '999',
          isActiveThree: '999',
          endOptionsUl: [],
          majorstwo: [],
          majorsthree: [],
          endSessionActive: [],
          endSessionFlag: false,
          dialogTableVisible: false,
          endSessionLength: 0
        }
      }
    },
    computed: {
//      邮件列表数据
      cardListRender () {
        for (let i = 0; i < this.cardList.length; i++) {
          let item = this.cardList[i]
          item.categoryText = this.categoryText(item)
          item.agentName = this.agentName(item)
          item.toPeerName = this.toPeer(item)
          item.chatTime = this.chatTime(item)
        }
        return this.cardList
      },
      navMenuState () {
        return this.$store.state.navMenuState || false
      }
    },
    methods: {
//      截取id生成index
      handleSplit (index) {
        return '/index/' + this.type + '/' + this.tabType + '/' + index
      },
      changeSearchStatus () { // 改变高级搜索选中搜索的状态
        if (contains(this.$store.state.session.user.funcIds, 'func_finish_undeal_email_session')) {
          this.shouFinshUndeal = true
        }
      },
//      卡片的点击事件
      handleSelect (index) {
        this.$store.commit('email/REFRESH_BUS_RIGHT', Math.random())
        this.$store.commit('BLANK', this.tabType)
        this.$emit('changeCardItem')
      },
//      邮件类别
      categoryText (item) {
        let result = ''
        let mailCategorys = this.$getCache('mailCategorys')
//        let categoryList = this.$store.state.session.dicMap.mailCategorys || []
        let categoryList = mailCategorys || []
        for (var i = 0; i < categoryList.length; i++) {
          if (categoryList[i]._id === item.category) {
            result = categoryList[i].categoryName
          }
        }
        return result
      },
//      坐席名称
      agentName (item) {
        let data = ''
        if (item.agent && this.$store.getters.agents[item.agent]) {
          data = this.$store.getters.agents[item.agent].displayName
        }
        return data
      },
//      渠道技能组
      toPeer (item) {
        let peerId = item.toPeer || item.ToPeer
        let peer = getEmailQueueCacheByKey('mailQueues', 'Exten', peerId)
        console.log(peer)
        let peerName = ''
        if (peer) {
          peerName = peer.DisplayName
        }
        return peerName
      },
//      会话时间
      chatTime (item) {
        let shortTime = timeFormat(item.createTime, 'card')
        return shortTime
      },
//      单选获取数组
      getChecked () {
        return this.cardList.filter(item => item.checked).map((item) => {
          return {_id: item._id, sid: item.from.addr}
        })
      },
//      导出邮件
      exportExcel (type) {
        // 高级搜索条件
        let data = {}
        if (this.batch.allChecked) {
          data = deepClone(this.$store.state.email.emailList.email_all.list)
        } else {
          data = {_id: {$in: this.batch.batchItem}}
        }
        if (this.tabType === 'business_undeal' || this.tabType === 'business_my') {
          data.flag = 'kf'
        }
        let headers = []
        this.exportDialog.headers.forEach((item) => {
          if (this.exportDialog.select.indexOf(item.value) !== -1) {
            headers.push(item.value)
          }
        })
        if (type === 'task') {
          this.$store.dispatch('addExportTask', {condition: data, headers}).then(() => {
            this.checkNone()
            this.exportDialog.isShow = false
          })
        } else {
          data.headers = headers
          let _exportObj = {
            name: this.$t('business.exportName') + this.getCurrentDateTime(),
            id: uuid.v1()
          }
          this.$store.commit(gtypes.SET_EXPORTLIST, _exportObj)
          this.$store.dispatch('exportBusiness', data).then(() => {
            this.$store.commit(gtypes.DEL_EXPORTLIST, _exportObj)
          })
          this.checkNone()
          this.exportDialog.isShow = false
        }
      },
      checkThis (checked, event) { // 单个选中传送数组和展示批量
        let checkedArr = this.getChecked()
        let isBatchShow = checkedArr.length > 0
        if (this.tabType === 'email_todo') {
          this.batch[this.tabType].allChecked = checkedArr.length === this.$store.state.email.todoNum
        } else {
          this.batch[this.tabType].allChecked = checkedArr.length === this.$store.state.email.emailList.email_all.count
        }
        this.batch[this.tabType].batchItem = checkedArr
        this.batch[this.tabType].isBatchShow = isBatchShow
        this.batch[this.tabType].checkedCount = checkedArr.length
      },
      checkAll () { // 全选&取消全选
        this.batch[this.tabType].isBatchShow = this.batch[this.tabType].allChecked
        let inputs = this.$el.getElementsByClassName('fbox')
        this.cardList.forEach((item) => {
          if (this.tabType === 'email_all' && item.status !== 'deal') {
            item.checked = this.batch[this.tabType].allChecked
          }
          if (this.tabType === 'email_todo') {
            item.checked = this.batch[this.tabType].allChecked
          }
        })
        for (let i = 0; i < inputs.length; i++) { // 升级之后有bug需要手动将checkbox调整为相应状态
          inputs[i].checked = this.batch[this.tabType].allChecked
        }
        this.batch[this.tabType].batchItem = this.getChecked()
        if (this.$store.state.email.emailList[this.tabType].more) {
          if (this.tabType === 'email_todo') {
            this.batch[this.tabType].checkedCount = this.batch[this.tabType].allChecked ? '多于' + this.$store.state.email.todoNum : 0
          } else {
            this.batch[this.tabType].checkedCount = this.batch[this.tabType].allChecked ? '多于' + this.$store.state.email.emailList.email_all.count : 0
          }
        } else {
          if (this.allCount) {
            this.batch[this.tabType].checkedCount = this.allCount
          } else {
            if (this.tabType === 'email_todo') {
              this.batch[this.tabType].checkedCount = this.batch[this.tabType].allChecked ? this.$store.state.email.todoNum : 0
            } else {
              this.batch[this.tabType].checkedCount = this.batch[this.tabType].allChecked ? this.$store.state.email.emailList.email_all.count : 0
            }
          }
        }
      },
//      取消全选
      checkNone () {
        this.batch[this.tabType].allChecked = false
        this.batch[this.tabType].batchItem = []
        this.batch[this.tabType].isBatchShow = false
        this.cardList.forEach((item) => {
          item.checked = false
        })
      },
//      点击批量结束会话按钮
      showFinishPopup () {
        this.$store.dispatch('getCache', {type: 'channelDic'}).then((res) => {
          let _dics = []
          res.forEach((item) => {
            if (item.type === 'email') {
              _dics = item.options || []
            }
          })
          if (_dics.length === 0) {
            this.$message.error(this.$t('email.isNullByFinishKey'))
            return
          }
          let two = false
          let three = false
          this.batchFinish.endSessionLength = 1
          _dics.forEach((item) => {
            if (!item.options) {
              item.options = []
            } else if (item.options.length) {
              two = true
            }
            item.options.forEach((secondItem) => {
              if (!secondItem.options) {
                secondItem.options = []
              } else if (secondItem.options.length) {
                three = true
              }
            })
          })
          if (two) {
            this.batchFinish.endSessionLength = 2
            if (three) {
              this.batchFinish.endSessionLength = 3
            }
          }
          this.batchFinish.endOptionsUl = _dics
          this.batchFinish.dialogTableVisible = true
          this.batchFinish.majorstwo = []
          this.batchFinish.majorsthree = []
          this.batchFinish.endSessionActive = []
          this.batchFinish.isActiveOne = ''
        })
      },
//      结束会话
      endSessionFun (flag) {
        if (flag) {
          if (this.batchFinish.endSessionFlag === false) {
            this.$message.error(this.$t('public.chooseEndSession'))
            return
          } else {
            let arr = this.batchFinish.endSessionActive
            let actName = ''
            let finishKey = ''
            if (arr.length > 2) {
              let one = arr[0]
              let two = arr[1]
              let three = arr[2]
              actName = this.batchFinish.endOptionsUl[one].options[two].options[three].name
              finishKey = this.batchFinish.endOptionsUl[one].options[two].options[three].key
            } else if (arr.length === 2) {
              let one = arr[0]
              let two = arr[1]
              actName = this.batchFinish.endOptionsUl[one].options[two].name
              finishKey = this.batchFinish.endOptionsUl[one].options[two].key
            } else {
              let one = arr[0]
              actName = this.batchFinish.endOptionsUl[one].name
              finishKey = this.batchFinish.endOptionsUl[one].key
            }
            if (this.tabType === 'email_todo') {
              let data = {
                finishReason: actName,
                finishKey: finishKey,
                finishiArr: deepClone(this.batch[this.tabType].batchItem)
              }
              this.$store.dispatch('finishEmailSession', data).then(() => {
                this.$router.replace({path: '/index/email'})
              })
              this.batchFinish.dialogTableVisible = false
              this.batchFinish.endSessionActive = []
              this.batchFinish.endSessionFlag = false
              this.checkNone()
            } else {
              let dataNew = {
                finishReason: actName,
                finishKey: finishKey
              }
              let finishiArr = deepClone(this.batch[this.tabType].batchItem)
              let arrNew = []
              finishiArr.forEach((item) => {
                arrNew.push(item._id)
              })
              if (this.batch[this.tabType].allChecked) {
                dataNew = Object.assign(dataNew, this.currentAdvSesrch)
              } else {
                dataNew.finishArr = arrNew
              }
              this.$store.dispatch('finishUndealEmailSession', dataNew).then((res) => {
                if (res.success) {
                  this.batchFinish.dialogTableVisible = false
                  this.batchFinish.endSessionActive = []
                  this.batchFinish.endSessionFlag = false
                  if (this.batch[this.tabType].checkedCount > 1000 || this.batch[this.tabType].checkedCount === '多于1000') {
                    this.$message.success(this.$t('email.finishUndealEmailSessionRes'))
                  }
                  this.checkNone()
                  this.$emit('refresh', true)
                }
              })
            }
          }
        } else {
          this.batchFinish.endSessionFlag = false
          this.batchFinish.dialogTableVisible = false
        }
      },
//      选择结束会话类型
      changeEndSessionFlag (value) {
        this.batchFinish.endSessionFlag = value
      },
//      客户状态名称
      statusName (status) {
        let custTmpls = this.$getCache('custTmpls')
        if (status && custTmpls[0]) {
          let cs = custTmpls[0].status[status]
          if (cs) {
            return cs
          } else {
            return status !== 'status_unknow' ? '--' : ''
          }
        } else {
          return ''
        }
      },
//      客户状态颜色
      currentColor (status) {
        let statusConfig
        let custTmpls = this.$getCache('custTmpls')
        if (custTmpls && custTmpls[0]) {
          statusConfig = custTmpls[0].statusConfig || custTmpls[0].status
        }
        if (status) {
          if (statusConfig && statusConfig[status]) {
            return statusConfig[status].color
          } else {
            return this.colors[status] ? this.colors[status] : '#009FE3'
          }
        }
      }
    },
    beforeMount () {
      if (this.$store.state.session.user.funcIds && contains(this.$store.state.session.user.funcIds, 'func_finish_undeal_email_session')) {
        this.shouFinshUndeal = true
      }
    }
  }
</script>
<style lang="stylus" scoped>
@import "../../../assets/common.styl"
  .el-menu-item
    color $cf-level2
    [class^="el-icon-"]
      margin-right 5px
  .email-card
    height 100%
  .el-menu-item
    height auto
    line-height inherit
    padding 0
  .custom-is-active
    background-color $c-pink
  .el-menu-item.custom-is-active
    background-color $c-card
  .el-menu-item.custom-is-active
    .card
      background-color $c-card-active
  .card:hover
    background-color $c-card-hover
  .card
    width 100%
    border-bottom 1px solid $c-border1
    background-color $cf-white
    display flex
    cursor pointer
    padding-left 10px
    box-sizing border-box
    over-flow hidden
    .e-ch-show
      visibility visible
    .ct
      display inline-block
      box-sizing border-box
      padding-top 16px
      margin-right 16px
    .info
      width calc(100% - 16px)
      li
        width 100%
        h4
          color $cf-gray2
          font-weight bold
        span
          color $cf-gray3
        .status_finish
          color $c-email
        .status_undeal
          color $followed-color
        .status_deal,
        .email_card_status,
        .email_chat_time
          color $cf-gray6
        .topeer_box
          color $cf-gray4
      .email_info_from
        margin-top 4px
        position relative
        height 16px
        line-height 16px
        .leak_num
          margin 0 6px
          border-radius 50%
          background #ff6b6b
          color #fff
          padding 0 6px
          height 16px
          display inline-block
          text-align center
          line-height 16px
        .email_card_flex
          .card_left,.card_right
            font-weight bold
      .email_info_subject
        line-height 20px
        height 20px
        margin-top 6px
    .remark
      flex 3
      ul
        float right
        margin-right 14px
        .email_info_category
          color $cf-gray4
          margin-top 21px
          span
            max-width 80px
            display inline-block
        li
          float right
          margin-top 10px
          text-align right
          width 100%
        .date_time_star
          margin-top 10px
        .email_status
          margin-top 10px
    .remark.all
      ul
        .email_info_category
          color $cf-gray4
          margin-top 15px
    .date
      color $cf-level2
    .info
      ul
        width 100%
        li
          width 100%
          .ellipsis
            width 100%
            display inline-block
    i
      font-style:normal
  .card_statu_li
    display inline-block
    text-align center
    border-radius 4px
  .el-menu-item.custom-is-active
    .el-icon-star-on
      color #459ae9
  .card:hover
  .card:active
    label
      visibility visible
  /*label
    visibility hidden*/
  label.visible
    visibility visible
  .email_info_addr
    margin-top -2px
  .email_info_other
    margin-top 4px
  .fake-checkbox
    left 6px
    top 9px
  .el-icon-star-on
    color #459ae9
    position absolute
    left -26px
  .ellipsis
    display inline-block
  .card_left
    flex-shrink 1
  .card_right
    flex-shrink 0
    margin-right 8px
  .visible
    .fake-label
      width 334px
      margin -12px 0 0 -12px
  .email_all
    .card
      height 75px
    .visible
      .fake-label
        height 75px
  .email_todo
    .card
      height 60px
    .visible
      .fake-label
        height 60px
  .email_card_flex
    display flex
    justify-content space-between
    .el-icon-star-on
      font-size 16px
</style>
